package com.maotai.llzhou.thread;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.llzhou.bean.MaotaiString;
import com.maotai.llzhou.bean.MaotaiWebCookie;
import com.maotai.llzhou.bean.Product512;
import com.maotai.llzhou.bean.ProductInfo;
import com.maotai.llzhou.service.MaotaiService;
import com.maotai.llzhou.util.FaceUtil;
import com.maotai.llzhou.util.HttpClientUtilNew;
import com.maotai.llzhou.util.IPFactory;
import com.maotai.llzhou.util.JSUtil;

/**
 * 登录并且抢购
 */
public class MaotaiYuYueThread512 extends Thread {

	@Resource(name = "maotaiService")
	private MaotaiService maotaiService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	private MaotaiWebCookie mwc;
//	private Map<String, Object> tokenMap;

	public MaotaiYuYueThread512(MaotaiService maotaiService,
			Map<String, Object> zhanghao, String ipAndPort,
			MaotaiWebCookie mwc) {
		super();
		this.maotaiService = maotaiService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
		this.mwc = mwc;
	}
//	public MaotaiYuYueThread(MaotaiService maotaiService,
//			Map<String, Object> zhanghao, String ipAndPort, MaotaiWebCookie mwc,
//			Map<String, Object> tokenMap) {
//		super();
//		this.maotaiService = maotaiService;
//		this.zhanghao = zhanghao;
//		this.ipAndPort = ipAndPort;
//		this.mwc = mwc;
//		this.tokenMap = tokenMap;
//	}

	public MaotaiWebCookie getMwc() {
		return mwc;
	}

	
//	public Map<String, Object> getTokenMap() {
//		return tokenMap;
//	}
//	public void setTokenMap(Map<String, Object> tokenMap) {
//		this.tokenMap = tokenMap;
//	}
	public void setMwc(MaotaiWebCookie mwc) {
		this.mwc = mwc;
	}

//	public String getIpAndPort() {
//		return ipAndPort;
//	}
//
//	public void setIpAndPort(String ipAndPort) {
//		this.ipAndPort = ipAndPort;
//	}

	public MaotaiService getMaotaiService() {
		return maotaiService;
	}

	public void setMaotaiService(MaotaiService maotaiService) {
		this.maotaiService = maotaiService;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	@Override
	public void run() {
		try {
			int mtBizId = 2;
			String code = zhanghao.get("code")+"";
			String addressId = zhanghao.get("addressId")+"";
			String memberId = zhanghao.get("memberId")+"";
			String auth = zhanghao.get("auth")+"";
			String zimId = "";
            String bizId = "";
            String name = zhanghao.get("name")+"";
            String certNumber = zhanghao.get("certNumber")+"";
            String provinceName = zhanghao.get("provinceName")+"";
            String cityName = zhanghao.get("cityName")+"";
            String token = zhanghao.get("token")+"";
			if(zhanghao.get("phone")==null){
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				return;
			}
			HttpClientUtilNew hcu = HttpClientUtilNew.getInstance();
			// 增加代理
			//http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=1&time=100&pro=江苏省&city=南京市&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=
//			String httpUrl = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=1&time=100&pro="+provinceName+"&city="+cityName+"&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=";
//			String httpUrl = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=1&time=100&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=";
//			JSONObject jObject = IPFactory
//					.getKdByUrl(httpUrl);
//			if(jObject.getString("msg").contains("为空")){
//				System.out.println(code+"--未获取到ip--"+jObject.getString("msg"));
//				httpUrl = "http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty=1&time=100&pro="+provinceName+"&port=1&format=json&ss=5&css=&dt=1&specialTxt=3&specialJson=";
//				jObject = IPFactory
//						.getKdByUrl(httpUrl);
//			}
//			if(jObject.getString("msg").contains("为空")){
//				return;
//			}
//			JSONArray jArray2 = jObject.getJSONArray("data");
//			JSONObject jj = (JSONObject) jArray2.get(0);
//			String ipAndPort = jj.getString("IP")+":"+jj.getIntValue("Port");
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);
			
			//查询预约情况
			String apply_query_url = MaotaiString.APPLY_QUERY_URL.replace("xxx", memberId);
			mwc = hcu.sendHttpGetProxy(apply_query_url, mwc, config, MaotaiString.APPLY_QUERY_REFERER);
			System.out.println(zhanghao.get("code")+" "+"账号查询预约情况--"+mwc.getContent());
			if(mwc.getContent().contains("login")){
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				return;
			}
			if(mwc.getContent().contains("错误")){
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				return;
			}
			//{"data":{"endRow":1,"firstPage":1,"hasNextPage":false,"hasPreviousPage":false,"isFirstPage":true,"isLastPage":true,"lastPage":1,"list":[{"address":"江苏省南京市江宁区天禄大道1号翠屏城73栋805室","addressId":"1179370534174015495","applyTime":"2018-07-30 12:59:27","areaCode":"320115000000","buyCycleDay":null,"channelName":null,"cityCode":"320100000000","createTime":"2018-07-30 12:59:27","detailed":"天禄大道1号翠屏城73栋805室","equipId":null,"failureDay":null,"failureTime":null,"goodsId":"1180731799931808771","goodsName":"【茅台商城预约购买】贵州茅台酒（新飞天）53%vol 500ml（商品编号：741）","goodsPicture":"https://prod-oss.emaotai.cn/supplychain-dev/test/img/jXftfKCbpH.jpg","id":"1182370414635126790","itemId":"1180731799924468740","orderNo":null,"platformId":"1","provinceCode":"320000000000","receivePhone":"13372007847","receiver":"周亮亮","registPhone":"13372007847","reviewInfo":null,"reviewLevel":"0","reviewTime":null,"reviewer":null,"shopId":"1173773178264259584","skuKv":{"香型（多选）":"酱香"},"status":"1","userId":"3586409","userName":"nickboowen"}],"navigatePages":8,"navigatepageNums":[1],"nextPage":0,"orderBy":null,"pageNum":1,"pageSize":5,"pages":1,"prePage":0,"size":1,"startRow":1,"total":1},"resultCode":0,"resultMsg":"success"}
			JSONObject jObject2 = JSONObject.parseObject(mwc.getContent());
			JSONObject data2 = jObject2.getJSONObject("data");
			JSONArray data3 = data2.getJSONArray("list");
			boolean hasYuYue = false;
			String status = "";
			if (data3 == null || data3.size() == 0) {
				System.out.println(zhanghao.get("code")+" "+"账号没有预约--");
			}else{
				for (int i = 0; i < data3.size(); i++) {
					JSONObject temp = data3.getJSONObject(i);
					//"goodsId": "1180731799931808771",这个是新飞天741
					//1187543793848641543 这个是五星92
					//1190618096943241218这个是狗茅512
					String goodsId = temp.getString("goodsId");
					if(!Product512.GOODSID.equals(goodsId)){
						continue;
					}
					status = temp.getString("status");
					if("1".equals(status)||"3".equals(status)){
						//有登记过，但是网点还没有接单
						hasYuYue = true;
						break;
					}else if("6".equals(status)){
						//有登记过，但是没有网点接单
						continue;
					}else if("4".equals(status)){
						//有登记过，网点接单
						//查询订单
						//已接单是4
						hasYuYue = true;
					}else if("2".equals(status)){
						//有登记过，网点接单
						//查询订单
						//已接单是4
						continue;
					}
				}
			}
			if(hasYuYue){
				return;
			}
			if("2".equals(status)){
				//修改地址
				/**
				 * deliveryName:康功栋
				address:日月天地大厦B座1901室跆拳道协会
				deliveryMobile:13112935251
				deliveryEmail:
				addressAlias:
				provinceCode:110000000000
				cityCode:110100000000
				areaCode:110106000000
				id:1181971912186910729
				defaultStatus:1
				 */
			}
			
			/**
			 * 新增扫脸功能
			 */
			Thread.sleep(100);
			//访问预约页面
			mwc = hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_BEGIN_URL512, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
			Thread.sleep(100);
			//点击预约
	        String signurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/switch?sign="+JSUtil.excuFunctionA("EMAOTAI_"+zhanghao.get("memberId"))+"&appCode=1&_t="+System.currentTimeMillis();
	        mwc = hcu.sendHttpGetProxy(signurl, mwc, config, MaotaiString.APPLY_BEGIN_REFERER_URL);
	        //2018-09-11
	        Thread.sleep(100);
	        //查询实名情况
	        String getauditurl = "https://i.emaotai.cn/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get?appCode=1&_t="+System.currentTimeMillis();
	        mwc = hcu.sendHttpGetProxy(getauditurl, mwc, config, MaotaiString.APPLY_END_REFERER_URL);
	        System.out.println(zhanghao.get("code")+"----获取实名情况-------"+mwc.getContent());
		    if(!mwc.getContent().contains("success")){
		    	zhanghao.put("initstatus", "x");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
            	return;
		    }
		    Thread.sleep(100);
		    //清除扫脸
		    String clearurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId="+mtBizId+"&appCode=1&_t="+System.currentTimeMillis();
			mwc = hcu.sendHttpGetProxy(clearurl,mwc,config,"");
			Thread.sleep(100);
			//打开二维码扫描
	        String compressurl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/compress?mtBizId="+mtBizId+"&faceverify=scan&auth="+auth+"&appCode=1&_t="+System.currentTimeMillis();
	        mwc = hcu.sendHttpGetProxy(compressurl, mwc, config, MaotaiString.APPLY_END_REFERER_URL);
	        System.out.println(zhanghao.get("code")+"----提示二维码页面-------"+mwc.getContent());
	       
	        //"data" : "EMAOTAI_20180817114945358596"
	        //https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/clear?mtBizId=2&appCode=1&_t=1535632636275
	        //TODO
	        Thread.sleep(5000);
	        if(mwc!=null && mwc.getContent()!=null){
	            JSONObject dataJ = JSONObject.parseObject(mwc.getContent());
	            String data = dataJ.getString("data");
	            System.out.println(zhanghao.get("code")+"-----------"+data);
	            String depressurl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/decompress?key="+data;
	            mwc = hcu.sendHttpGetProxy(depressurl,mwc,config,null);
	            System.out.println(zhanghao.get("code")+"----扫描二维码结束----"+mwc.getContent());
	               
	            if(mwc.getContent()!=null && mwc.getContent().contains("success")){

	            }else if(mwc.getContent()!=null && mwc.getContent().contains("无缓存数据")){

	            }else{
	                return;
	            }
	        
	        }
	        Thread.sleep(100);
	        //新增手机端查询实名情况
	        String auditUrl = "https://i.cmaotai.com/yundt-application-trade-core/api/v1/yundt/trade/memberdoc/audit/get?";
	        mwc = hcu.sendHttpGetAppProxy(auditUrl,mwc,config,null);
	        System.out.println(zhanghao.get("code")+"----手机端获取实名情况-------"+mwc.getContent());
		    if(!mwc.getContent().contains("success")){
		    	zhanghao.put("initstatus", "x");
				maotaiService.updateZhanghaoInitStatus(zhanghao);
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
            	return;
		    }
		    
	        //获得metainfo
	        JSONObject uploadJ = new JSONObject();
	        uploadJ.put("apdidToken",token+""+code) ;
	        uploadJ.put("appName","com.emaotai.ysapp") ;
	        uploadJ.put("appVersion",ProductInfo.PRODUCT_VERSION) ;
	        uploadJ.put("bioMetaInfo","3.3.0:98304,0") ;
	        uploadJ.put("deviceModel","M8"+code) ;
	        uploadJ.put("deviceType","android") ;
	        uploadJ.put("osVersion","6.0.1") ;
	        uploadJ.put("zimVer","1.0.0") ;
	        //System.out.println(uploadJ.toJSONString());
	        //将metainfo传到茅台服务端，得到 "zimId" : "e1570236d1cee15043f1823e202d628b",
	        Thread.sleep(100);
	        //采用最新的post
	        String initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/init";
	        String postData = "auditType=1&certNumber="+certNumber+"&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName="+URLEncoder.encode(name,"utf-8");
	        //String postData = "auditType=1&certNumber=320922198607240034&metainfo="+URLEncoder.encode(uploadJ.toJSONString())+"&mtBizId="+mtBizId+"&userName=%E5%91%A8%E4%BA%AE%E4%BA%AE";
	         for(int i=0;i<20;i++) {
	        	 mwc = hcu.sendHttpPostAppProxy(initUrl, mwc, postData, config);
	            System.out.println(zhanghao.get("code")+"----初始化预约摄像头----" + mwc.getContent());
	            if (mwc.getContent().contains("繁忙")||mwc.getContent().contains("失败")||mwc.getContent().contains("抱歉")){
	            	zhanghao.put("yuyuestatus", "x");
					 maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
					 return;
	            }
	            if (mwc.getContent().contains("重试")||mwc.getContent().contains("抱歉")||mwc.getContent().contains("query")) {
	            	zhanghao.put("yuyuestatus", "x");
					 maotaiService.updateZhanghaoYuYueStatus(zhanghao);
					 return;
	            } else {
	                break;
	            }
	        }
	         if (mwc.getContent().contains("重试")){
	        	 //证明脸黑了
	        	 zhanghao.put("yuyuestatus", "x");
				 maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				 return;
	         }
	        if(mwc!=null && mwc.getContent()!=null){
	            JSONObject initJson = JSON.parseObject(mwc.getContent()).getJSONObject("data");
	            zimId = initJson.getString("zimId");
	            bizId = initJson.getString("bizId");
	            
	        }
	        //然后发起认证，认证完了回传到茅台服务器
            //最后提交预约信息
	        if("".equals(zimId)||"".equals(bizId)) {
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
	        	return;
	        }
	        
	        boolean isFace = FaceUtil.faceToken(token,zimId,config,zhanghao);
	        if(!isFace){
	        	zhanghao.put("yuyuestatus", "7");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
	        	return;
	        }
	        Thread.sleep(3000);
	        initUrl = "https://i.cmaotai.com/huieryun-identity/api/v1/authant/faceverify/query?zimId="+zimId+"&bizId="+bizId+"&mtBizId="+mtBizId+"&auditType=1";
	        mwc = hcu.sendHttpGetAppProxy(initUrl,mwc,config,null);
	        System.out.println(zhanghao.get("code")+"----识别结束提交服务器----"+mwc.getContent());
	        if(mwc.getContent().contains("身份")){
	        	zhanghao.put("yuyuestatus", "M");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
	        	return;
	        }
	        Thread.sleep(100);
	        //20180825茅台改为网页去验证，不在手机端提交查询
	        String refererurl = "https://www.emaotai.cn/smartsales-b2c-web-pc/sign/signUp?info=eyJpdGVtTmFtZSI6IuOAkOiMheWPsOWVhuWfjumihOe6pui0reS5sOOAkei0teW3nuiMheWPsOmFku%2b8iOaWsOmjnuWkqe%2b8iTUzJXZvbCA1MDBtbO%2b8iOWVhuWTgee8luWPt%2b%2b8mjc0Me%2b8iSIsImltZ1VybCI6Imh0dHBzOi8vcHJvZC1vc3MuZW1hb3RhaS5jbi9zdXBwbHljaGFpbi1kZXYvdGVzdC9pbWcvQ3lma2RuUDVGcy5qcGciLCJza3VJZCI6IjExODA3MzE3OTk5MzE4MDg3NzEiLCJpdGVtSWQiOiIxMTgwNzMxNzk5OTI0NDY4NzQwIiwic2hvcElkIjoiMTE3Mzc3MzE3ODI2NDI1OTU4NCJ9";

	        //https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId=2&appCode=1&_t=1535153490878
	        initUrl = "https://i.emaotai.cn/huieryun-identity/api/v1/authant/faceverify/qrquery?mtBizId=2&appCode=1";
	        mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);
	        Thread.sleep(100);
	        System.out.println(zhanghao.get("code")+"----查询识别结果----"+mwc.getContent());
	        if(mwc!=null && !mwc.getContent().contains("success")){
	            System.out.println("识别结果未成功");
	            for(int i=0;i<5;i++){
	            	mwc = hcu.sendHttpGetProxy(initUrl,mwc,config,refererurl);
	                System.out.println("maotaiAppCookie---"+mwc.getContent());
	                if(mwc!=null && mwc.getContent().contains("success")){
	                    break;
	                }
	            }
	        }
	        
	        //add by llzhou at 2018-09-02
			/**
			 * 	memberId:3586409
				goodsId:1180731799931808771
				shopId:1173773178264259584
				itemId:1180731799924468740
				addressId:1179370534174015495
			 */
			
			//后期可以增加先访问预约页面
			//TODO
			//带cookie访问预约页面
			
	        Thread.sleep(100);
			//然后提交预约
			Map<String, String> orderMap = new HashMap<String, String>();
			orderMap.put("memberId", memberId);
			orderMap.put("goodsId", Product512.GOODSID);
			orderMap.put("shopId", Product512.SHOPID);
			orderMap.put("itemId", Product512.ITEMID);
			orderMap.put("addressId", addressId);
			String applyUrl = "https://i.emaotai.cn/cmaotai-application-ysdt/api/v1/ysdt/activity/user/applyFace?appCode=1&_t="+System.currentTimeMillis();
//			hcu.sendHttpOptionProxy(applyUrl, mwc, config, MaotaiString.APPLY_REFERER);
			mwc = hcu.sendHttpPostProxy(applyUrl, mwc,
					orderMap,
					config,MaotaiString.APPLY_REFERER);
			if(mwc.getContent().contains("login")){
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				zhanghao.put("loginstatus", "0");
				maotaiService.updateZhanghaoLoginStatus(zhanghao);
				return;
			}
			if(mwc.getContent().contains("操作失败")){
				zhanghao.put("yuyuestatus", "4");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				return;
			}if(mwc.getContent().contains("已结束")){
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
				return;
			}
			System.out.println(zhanghao.get("code")+"--"+ipAndPort+"提交狗毛预约情况--"+mwc.getContent());
			
			//核对返回预约结果
			
			//提交预约之后，再访问下页面
			Thread.sleep(1000);
			if(mwc.getContent().contains("success")){
				mwc=hcu.sendHttpGetProxyIndex(MaotaiString.APPLY_END_URL, mwc, config, MaotaiString.APPLY_END_REFERER_URL);
//				System.out.println(mwc.getContent());
			}
//			MaotaiYuYueThread512_ji myyt = new MaotaiYuYueThread512_ji(maotaiService,zhanghao,ipAndPort,mwc);
//			myyt.start();
		} catch (Exception e) {
//			e.printStackTrace();
			System.out.println(zhanghao.get("code")+" : throws yuyue exception ");
			try {
				zhanghao.put("yuyuestatus", "0");
				maotaiService.updateZhanghaoYuYueStatus512(zhanghao);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}



}
